import { TypeConstants } from '../TypeConstants';
import { ReaderIn } from '../ReaderIn';
import { ITypeAdapter } from './ITypeAdapter';
import { WriterOut } from '../WriterOut';
import { IDefault } from '../default/IDefault';
import { isBoolean, isNumber, isString } from '../utils/TypeUtils';
import { NumberDefault } from '../default/NumberDefault';
import { StringDefault } from '../default/StringDefault';
import { BooleanDefault } from '../default/BooleanDefault';
import { DlJsonDefault } from '../default/DlJsonDefault';

export class DefaultTypeAdapter implements ITypeAdapter {
  write(writerOut: WriterOut): WriterOut {
    writerOut.setWriteValue(writerOut.getTarget())
    return writerOut
  }

  typeConstants(): TypeConstants {
    return TypeConstants.TYPE_DEFAULT
  }

  read(readerIn: ReaderIn): ReaderIn {
    let defaultT = this.getDefault(readerIn.getTarget(), readerIn.getJson())
    readerIn.setValue(defaultT.asTargetType())
    return readerIn
  }

  private getDefault(target: ESObject, json: ESObject): IDefault<ESObject> {
    if (isNumber(target)) {
      return new NumberDefault(json)
    } else if (isString(target)) {
      return new StringDefault(json)
    } else if (isBoolean(target)) {
      return new BooleanDefault(json)
    } else {
      return new DlJsonDefault()
    }
  }
}